package com.leadingsoft.web.file.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.leadingsoft.common.constant.Constant;
import com.leadingsoft.core.dto.ResultType;
import com.leadingsoft.core.mapper.FileCustomMapper;
import com.leadingsoft.core.mapper.FileMapper;
import com.leadingsoft.core.pojo.File;
import com.leadingsoft.core.pojo.FileExample;
import com.leadingsoft.core.pojo.FileExample.Criteria;

@Service
public class FileListService {
	@Autowired
	private FileMapper fileMapper;
	@Autowired
	private FileCustomMapper fileCustomMapper;
	@Value("${base.path}")
	private String basePath;

	public String getFileList(Long thisIndex, Integer userId) {
		FileExample fileExample = new FileExample();
		Criteria criteria = fileExample.createCriteria();
		criteria.andParentFileIdEqualTo(thisIndex);
		criteria.andAddUserEqualTo(userId);
		criteria.andDelFlagEqualTo(Constant.IS_EXIST);
		fileExample.setOrderByClause("edit_time desc");
		List<File> files = fileMapper.selectByExample(fileExample);
		if (CollectionUtils.isNotEmpty(files)) {
			return ResultType.success(files);
		} else {
			return ResultType.fail("没有文件");
		}
	}
	public boolean check(File file, boolean isUpdate) {
		FileExample fileExample = new FileExample();
		Criteria criteria = fileExample.createCriteria();
		criteria.andDelFlagEqualTo(Constant.IS_EXIST);
		criteria.andParentFileIdEqualTo(file.getParentFileId());
		criteria.andAddUserEqualTo(file.getAddUser());
		criteria.andFileNameEqualTo(file.getFileName());
		criteria.andFileTypeEqualTo(file.getFileType());
		List<File> files = fileMapper.selectByExample(fileExample);
		if (isUpdate) {
			if (null != files && files.size() > 1) {
				return false;
			} else {
				return true;
			}
		} else {
			if (null != files && files.size() > 0) {
				return false;
			} else {
				return true;
			}
		}
	}
	public boolean checkFile() {
		return true;
	}
	public String createFolder(String parentIndexList, Long thisIndex, String folderName, Integer userId) {
		File file = new File();
		Date nowDate = new Date();
		file.setParentFileId(thisIndex);
		file.setParentFileIds(parentIndexList);
		file.setFileName(folderName);
		file.setFileType(Constant.FOLDER);
		file.setFileIcon(Constant.FOLDER_ICON);
		file.setFilePath(null);
		file.setFileVersion(null);
		file.setAddUser(userId);
		file.setAddTime(nowDate);
		file.setEditTime(nowDate);
		file.setDelFlag(Constant.IS_EXIST);
		if (check(file, false)) {
			fileMapper.insertSelective(file);
			return ResultType.success();
		} else {
			return ResultType.fail("文件名重复，不允许创建");
		}
	}
	public String renameFile(Long thisIndex, String fileName) {
		File file = fileMapper.selectByPrimaryKey(thisIndex);
		String originFileName = file.getFileName();
		file.setFileName(fileName);
		if (check(file, true)) {
			Byte fileType = file.getFileType();
			if (Constant.FILE == fileType) {
				try {
					// 修改文件名称
					String sourceFilePath = file.getFilePath();
					String targetFIlePath = sourceFilePath.replace(originFileName, fileName);
					FileUtils.copyFile(new java.io.File(sourceFilePath), new java.io.File(targetFIlePath));
					FileUtils.forceDelete(new java.io.File(sourceFilePath));
					file.setFilePath(targetFIlePath);
					file.setEditTime(new Date());
					fileMapper.updateByPrimaryKeySelective(file);
					return ResultType.success();
				} catch (IOException e) {
					e.printStackTrace();
					return ResultType.fail("文件改名失败");
				}
			} else if (Constant.FOLDER == fileType) {
				file.setEditTime(new Date());
				fileMapper.updateByPrimaryKeySelective(file);
				return ResultType.success();
			} else {
				return ResultType.fail("请求参数出现问题");
			}
		} else {
			return ResultType.fail("文件名重复，不允许更新");
		}
	}
	public String saveFileOnStandAlone1(MultipartFile[] files, String parentIndexList, Long thisIndex, Integer userId) {
		// 单机版上传文件，到本地目录
		if (null != files && files.length > 0) {
			for (MultipartFile file : files) {
				String originalFilename = file.getOriginalFilename();
				// 用户ID/父文件夹ID/
				StringBuilder path = new StringBuilder(basePath);
				path.append(userId).append("/").append(thisIndex).append("/");
				path.append(originalFilename);
				File fileObject = new File();
				Date nowDate = new Date();
				fileObject.setParentFileId(thisIndex);
				fileObject.setParentFileIds(parentIndexList);
				fileObject.setFileName(originalFilename);
				fileObject.setFileType(Constant.FILE);
				fileObject.setFileIcon(Constant.CONTENT_TYPE.get("other"));
				Constant.CONTENT_TYPE.forEach((k, v) -> {
					if (file.getContentType().equals(k)) {
						fileObject.setFileIcon(v);
					}
				});
				fileObject.setFilePath(path.toString());
				fileObject.setFileVersion(null);
				fileObject.setAddUser(userId);
				fileObject.setAddTime(nowDate);
				fileObject.setEditTime(nowDate);
				fileObject.setDelFlag(Constant.IS_EXIST);
				if (check(fileObject, false)) {
					try {
						FileUtils.writeByteArrayToFile(new java.io.File(path.toString()), file.getBytes(), false);
						fileMapper.insert(fileObject);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return ResultType.success();
		} else {
			return ResultType.fail("请上传至少一个文件");
		}
	}
	public void saveFileOnCluster(MultipartFile[] files) {
		// 上传文件到集群
	}
	public String deleteToTrash(Long[] thisIndexs) {
		if (null != thisIndexs && thisIndexs.length > 0) {
			for (Long thisIndex : thisIndexs) {
				fileCustomMapper.deleteFileToTrash(thisIndex);
			}
			return ResultType.success();
		} else {
			return ResultType.fail("请至少选中一个文件进行删除操作！");
		}
	}
	public String moveFile() {
		return null;
	}
	public String copyFile() {
		return null;
	}
}
